<!--第一天  5、属性计算和属性监听-->
<script setup lang="ts">
import {computed, reactive, ref, watch, watchEffect} from "vue";

let firstName = ref<string>('')
let secondName = ref<string>('')
let fullName = ref<string>('')


// 属性计算
// （1）只有get方法
/*let fullName=computed(()=>{
  return firstName.value+secondName.value
})*/
// （2）有get和set方法
/*let fullName=computed({
  get(){
    return firstName.value+secondName.value
  },
  set(){
  }
})*/




// 属性监听     如果监听的属性为ref声明的响应式数据，直接写属性名,不用加.value
// 监听一个属性
/*watch(firstName,(newVal,oldVal)=>{
  // console.log('监听')
  // console.log(newVal)
  // console.log(oldVal)

  fullName.value=newVal+secondName.value
  // fullName.value=firstName.value+secondName.value
})*/
// 监听两个属性     监听多个，写成数组形式
/*watch([firstName,secondName],(newVal,oldVal)=>{
  // console.log('监听')
  console.log(newVal)
  console.log(oldVal)

  fullName.value=newVal[0]+newVal[1]
},{       //深度监听
  deep:true,
  immediate:true
})*/


// 如果监听的属性为reactive声明的响应式数据,要使用箭头函数的形式()=>
/*interface ObjType{
  name:string,
  age:number
}
let obj=reactive<ObjType>({
  name:'张三',
  age:20
})
watch([firstName,secondName,()=>obj.age],(newVal,oldVal)=>{
  // console.log('监听')
  console.log(newVal)
  console.log(oldVal)

  fullName.value=newVal[0]+newVal[1]
},{
  deep:true,
  immediate:true
})*/

//用ref  ，直接写属性名
interface ObjType {
  name: string,
  age: number
}
let obj1 = ref<ObjType>({
  name: '李四',
  age: 10
})
watch([firstName, secondName,obj1.value], (newVal, oldVal) => {     //obj1.name打印不出来，只能打印出来obj1
  // console.log('监听')
  console.log(newVal)
  console.log(oldVal)

  fullName.value = newVal[0] + newVal[1]
}, {
  deep: true,
  immediate: true
})


/*// watchEffect   监听所有响应式数据
interface ObjType{
  name:string,
  age:number
}
let obj=reactive<ObjType>({
  name:'张三',
  age:20
})
let obj1=ref<ObjType>({
  name:'李四',
  age:10
})
watchEffect(()=>{
  console.log('watchEffect')
  fullName.value=firstName.value+secondName.value
})*/
</script>


<template>
  计算监听
  <p>姓：<input type="text" v-model="firstName">
    名：<input type="text" v-model="secondName">
    姓名：<input type="text" v-model="fullName"></p>
</template>

<style scoped>

</style>
